package com.coderg.gmall.product.util;

import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description
 * @Author CoderG
 * @Date 2025/5/21 2:24
 **/
public class FileUtil {
    static {
        try {
            //加载配置文件
            ClassPathResource classPathResource = new ClassPathResource("tracker.properties");
            //初始化fastdfs对象
            ClientGlobal.init(classPathResource.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String fileUpload(MultipartFile file) throws Exception {

        //初始化trackerclient
        TrackerClient trackerClient = new TrackerClient();
        //获取服务连接信息
        TrackerServer connection = trackerClient.getConnection();
        //初始化storageClient
        StorageClient storageClient = new StorageClient(connection, null);
        //获取文件拓展名
        String fileName = StringUtils.getFilenameExtension(file.getOriginalFilename());
        /**
         * 1.文件字节码
         * 2.文件拓展名
         * 3.附加参数
         * 4.返回结果为数组:0:组名  1:文件的完全路径名+文件名
         */
        String[] strings = storageClient.upload_file(file.getBytes(), fileName, null);
        //返回文件全量访问路径
        return strings[0] + "/" + strings[1];

    }

    /**
     * 文件下载
     * @return
     */
    public static byte[] fileDownload(String groupName, String path) throws Exception{

        //初始化trackerclient
        TrackerClient trackerClient = new TrackerClient();
        //获取服务连接信息
        TrackerServer connection = trackerClient.getConnection();
        //初始化storageClient
        StorageClient storageClient = new StorageClient(connection, null);

        byte[] bytes = storageClient.download_file(groupName, path);

        return bytes;
    }

    /**
     * 文件删除
     * @return
     */
    public static boolean deleteFile(String groupName, String path) throws Exception {
        //初始化trackerclient
        TrackerClient trackerClient = new TrackerClient();
        //获取服务连接信息
        TrackerServer connection = trackerClient.getConnection();
        //初始化storageClient
        StorageClient storageClient = new StorageClient(connection, null);

        int i = storageClient.delete_file(groupName, path);
        //i==0 success
        return i==0;
    }

    public static void main(String[] args) throws Exception {
        boolean result = deleteFile("group1", "M00/00/03/wKjIgGgs0CmAQJeqAABGGNLEJQo305.jpg");
        System.out.println(result);
    }
}
